import { Card, Form, Input, Button,message, Checkbox } from "antd";

import logo from "../../assets/logo.png";
import styles from "./index.module.scss";
import {useDispatch} from "react-redux"
import {login} from "@/store/actions/login"
import {useState} from 'react'
import { useHistory } from "react-router-dom";

const Login = () => {
    const rules = {
      mobile :[
            {
                required:true,
                message:'手机号为必填项'
            },
            {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对'
            }],
        code:[
            { len: 6, message: '验证码6个字符', validateTrigger: 'onBlur' },
            { required: true, message: '请输入验证码' }
          ],
          agree:[{validator(rule,value){
            if(value) {
              return Promise.resolve()
            } else {
              return Promise.reject(new Error('请阅读并同意协议'))
            }
           }}]
    }

    const dispatch = useDispatch()
    // loading的状态
    const [isLoading,setIsLoading] = useState(false)
     const history = useHistory()
    const onFinish = async (val)=>{
      try {
        setIsLoading(true)
        // dispatch 是异步的 下面的代码不会等待，而是直接执行，所以要用await
       await dispatch(login(val))
       message.success('登录成功',1,()=>{
        //  push可以退回
        //  history.push('/')
        //  replace不允许退回
        
        const pathName =  history.location.state.from || '/' 
        // console.log(pathName)
         history.replace(pathName)
      })
      } catch (e){
        message.error(e.response.data.message||'登录失败' ,3)
        // finally 无论结果怎样都会执行
      } finally {
        setIsLoading(false)
    } 
   }

  return (
    <div className={styles.root}>
      <Card className="login-container">
        {/* 图片 */}
        <img className="login-logo" src={logo} alt="" />
        {/* 表单 */}
        <Form autoComplete="off" size="large" validateTrigger={['onBlur']} onFinish={onFinish} initialValues={{mobile:'13911111111',code:'246810',agree:true}}>
          <Form.Item name="mobile" rules={rules.mobile}>
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
           name="code"
           rules={rules.code}
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item name="agree" valuePropName="checked" rules={rules.agree}>
            <Checkbox >我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={isLoading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
